<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item to="/admin/index">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-divider></el-divider>

        <!-- 管理信息 -->
        <div class="box">
            <el-row>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <h3 style="line-height:32px;">
                            <i class="el-icon-s-tools"></i> &nbsp; 管理信息
                        </h3>
                    </div>
                </el-col>
                <el-col :span="16" style="text-align: right;">
                    <div class="grid-content bg-purple">
                        <el-button size="small" type="primary" icon="el-icon-circle-plus-outline" @click="addDialogVisible = true">新增角色</el-button>
                    </div>
                </el-col>
            </el-row>
            <div class="divider"></div>

            <el-row :gutter="15" class="whererow">
                <el-col :span="4" style="line-height:32px;">当前共{{ countUsers }}个角色信息。</el-col>
            </el-row>

        </div>

         <!-- 列表开始 --------------------------------------------------------------->
        <el-table border ref="multipleTable" :data="tableData"
            tooltip-effect="dark" style="width: 100%">
            <el-table-column align="center" type="selection" width="55"> </el-table-column>
            <el-table-column align="center" label="编号" width="60">
                <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column align="center" label="角色名称" width="160">
                <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column align="center" label="角色描述">
                <template slot-scope="scope">{{ scope.row.description }}</template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="200">
                <template slot-scope="scope">{{ scope.row.gmtCreate }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="170">
                <template slot-scope="scope">
                    <el-button title="分配权限" type="success" size="mini" icon="el-icon-edit" circle @click="$router.push('/auth/permissionassignment')"></el-button>
                    <el-button title="编辑角色" type="warning" size="mini" icon="el-icon-edit" circle @click="editDialogVisible = true"></el-button>
                    <el-button title="删除角色" type="danger" size="mini" icon="el-icon-delete" circle @click="openDeleteConfirm(scope.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>
      <!-- 列表结束 --------------------------------------------------------------->

        
        <!-- 新增角色的弹窗 -->
        <el-dialog width="40%" title="添加角色" :visible.sync="addDialogVisible" :modal-append-to-body="false">
            <el-row>
                <el-col :span="24">
                    <el-form ref="ruleForm" :model="ruleForm" label-width="80px" size="small">
                        <el-form-item label="角色名称">
                            <el-input v-model="ruleForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述">
                            <el-input type="textarea" v-model="ruleForm.description"></el-input>
                        </el-form-item>
                        <el-form-item size="large">
                            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>

        <!-- 修改角色的弹窗 -->
        <el-dialog width="40%" title="修改角色" :visible.sync="editDialogVisible" :modal-append-to-body="false">
            <el-row>
                <el-col :span="24">
                    <el-form ref="form" :model="causer" label-width="80px" size="small">
                        <el-form-item label="角色名称">
                            <el-input v-model="causer.name"></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述">
                            <el-input type="textarea" v-model="causer.description"></el-input>
                        </el-form-item>
                        <el-form-item label="是否启用">
                            <el-radio-group v-model="causer.enable">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item size="large">
                            <el-button type="primary">保存</el-button>
                            <el-button>取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            causer:{
              name: '',
              description: '',
            },
          ruleForm: {
              name: '',
              description: '',
            },
            addDialogVisible: false,
            editDialogVisible: false,
            roleDialogVisible: false,
            selectRoles: '',
            countUsers:'',

            currentPage: 3,
            input: '',
            value: '',
            options: [{
                value: 'enable',
                label: '启用'
            },{
                value: 'disable',
                label: '禁用'
            }],
            tableData: [{
                id: '',
                name: '',
                description: '',
                gmtCreate: ''
            }]
        }
    },
    methods: {
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
        },
        loadRoles() {
        console.log('loadRoles()');
        let url = 'http://localhost:9081/roles';
        console.log('url = ' + url);
        let jwt = localStorage.getItem('jwt');
        console.log('jwt = ' + jwt);
        this.axios
            .create({headers: {'Authorization': localStorage.getItem('jwt')}})
            .get(url).then((response) => {
          let json = response.data;
          if (json.code == 20000) {
            this.tableData = json.data;
              console.log( this.tableData )
            this.countUsers = this.tableData.length

          } else {
            this.$message.error(response.data.message);
          }
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url = 'http://localhost:9081/roles/add-new';
            console.log('url >>> ' + url);
            let data = {
              'name': this.ruleForm.name,
              'description': this.ruleForm.description,
            };
            let jwt = localStorage.getItem("jwt")
            console.log('data >>> '+data);
            console.log('jwt>>>'+jwt);
            this.axios
                .create({headers: {'Authorization': localStorage.getItem('jwt')}})
                .post(url, data).then((response) => {
              console.log(response.data.code);
              if (response.data.code == 20000) {
                // 提示登录成功
                this.$message({
                  message: '登录成功！',
                  type: 'success'
                });
                // 获取服务器端响应的JWT并存入到LocalStorage中
                let jwt = response.data.data;
                console.log(jwt);
                localStorage.setItem('jwt', jwt);
                // 跳转到主页
                this.loadRoles();
              } else {
                this.$message.error('登录失败，用户名或密码错误！');
              }
            }).catch(function () {
              console.log('响应结果为失败！');
            })
          } else {
            alert('error submit!!');
            return false;
          }
        });
      },
      openDeleteConfirm(id) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleDelete(id);
        }).catch(() => {
        });
      },
      handleDelete(id) {
        console.log('将删除id=' + id + "的角色数据……");
        let url = 'http://localhost:9081/roles/' + id + '/delete';
        this.axios
            .create({headers: {'Authorization': localStorage.getItem('jwt')}})
            .post(url).then((response) => {
          let json = response.data;
          if (json.code == 20000) {
            this.$message({
              message: '删除角色成功！',
              type: 'success'
            });
          } else {
            this.$message.error(response.data.message);
          }
          this.loadRoles();
        }).catch(() => {
          // 执行到此处，通常是没有权限，例如没有携带JWT，被服务器端视为未登录，或当前登录的账号确实无权限
          this.$message.error('删除管理员失败，服务器忙，请稍后再次尝试！');
        });
      },
    },
  mounted() {
    // mounted >>> 已挂载，将在created之后、显示页面之前执行
    console.log('vue mounted');
    this.loadRoles();
  }

}
</script>
